package link.ten_fei.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import link.ten_fei.Bean.Doc_User;
import link.ten_fei.service.UserLoginService;
import link.ten_fei.service.UserLoginServiceImpl;
import link.ten_fei.util.CookieUtil;
import link.ten_fei.util.MD5Util;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置前端页面传递回来的字符编码
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		// 根据输入框标签name获取用户名与密码
		String action = request.getParameter("action");

		String doc_username = request.getParameter("username");
		String doc_password = MD5Util.encodeByMD5(request.getParameter("password"));
		String remember = request.getParameter("remember");
		// 查询用户的登录名与密码是否正确
		UserLoginService userLoginService = new UserLoginServiceImpl();
		Doc_User doc_User = userLoginService.findByNamAndPass(doc_username, doc_password);
		if (doc_User == null && action != null && action.equals("ajax")) {
			response.setCharacterEncoding("utf-8");
			PrintWriter writer = response.getWriter();
			writer.print("用户名或密码错误！！！");

		} else if (doc_User != null && (action == null || action == "")) {
			// 保存用户信息,有效时间为120分钟
			request.getSession().setAttribute("session_user", doc_User);
			// 记住密码，记住一个礼拜
			if (remember != null && remember.equals("remember-me")) {
				CookieUtil.addCookie("cookie_name_pass", 7 * 24 * 60 * 60, request, response,
						URLEncoder.encode(doc_username, "utf-8"), URLEncoder.encode(doc_password, "utf-8"));
			}
			// 登录成功跳转到主页
			request.getRequestDispatcher("/WEB-INF/jsp/main.jsp").forward(request, response);
		}
	}

}
